var $businessTable = $('#businessTable');

$(function(){
    barInitData("");//商机数据总览
    businessMess();//商机数据统计
    oppContractProportion('');//商机占比
    oppContractTypeProportion('');//商机类型
    oppTurnoverProportion('');
    businessTableInit('');
    rank(1);
})

//防止表头与表格不对齐
$(window).resize(function () {
    $businessTable.bootstrapTable('resetView');
});

/**
 *客户意向时间切换
 */
function clientSelectTime(time){
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.topMonth').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.week').removeClass('active-second');
        $("#clientDataType").val("all");
        barInitData("")
    }
    if (time == 'topMonth') {//上月
        $('.topMonth').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.week').removeClass('active-second');
        $("#clientDataType").val("thisLastMonth");
        barInitData("thisLastMonth");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.topMonth').removeClass('active-second');
        $('.week').removeClass('active-second');
        $("#clientDataType").val("thisMonth");
        barInitData("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.topMonth').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#clientDataType").val("thisWeek");
        barInitData("thisWeek");
    }
}
//商机占比
function percentageSelectTime(time){
    if (time == 'all') {//全部
        $('.percentAll').addClass('active-second');
        $('.percentTopMonth').removeClass('active-second');
        $('.percentMonth').removeClass('active-second');
        $('.percentWeek').removeClass('active-second');
        $("#percentDataType").val("all");
        oppContractProportion("")
    }
    if (time == 'topMonth') {//上月
        $('.percentTopMonth').addClass('active-second');
        $('.percentAll').removeClass('active-second');
        $('.percentMonth').removeClass('active-second');
        $('.percentWeek').removeClass('active-second');
        $("#percentDataType").val("thisLastMonth");
        oppContractProportion("thisLastMonth");
    }
    if (time == 'month') {//本月
        $('.percentMonth').addClass('active-second');
        $('.percentAll').removeClass('active-second');
        $('.percentTopMonth').removeClass('active-second');
        $('.percentWeek').removeClass('active-second');
        $("#percentDataType").val("thisMonth");
        oppContractProportion("thisMonth");
    }
    if (time == 'week') {//本周
        $('.percentWeek').addClass('active-second');
        $('.percentAll').removeClass('active-second');
        $('.percentTopMonth').removeClass('active-second');
        $('.percentMonth').removeClass('active-second');
        $("#percentDataType").val("thisWeek");
        oppContractProportion("thisWeek");
    }
}
//商机类型
function typeSelectTime(time){
    if (time == 'all') {//全部
        $('.percentTypeAll').addClass('active-second');
        $('.percentTypeTopMonth').removeClass('active-second');
        $('.percentTypeMonth').removeClass('active-second');
        $('.percentTypeWeek').removeClass('active-second');
        $("#percentTypeDataType").val("all");
        oppContractTypeProportion("")
    }
    if (time == 'topMonth') {//上月
        $('.percentTypeTopMonth').addClass('active-second');
        $('.percentTypeAll').removeClass('active-second');
        $('.percentTypeMonth').removeClass('active-second');
        $('.percentTypeWeek').removeClass('active-second');
        $("#percentTypeDataType").val("thisLastMonth");
        oppContractTypeProportion("thisLastMonth");
    }
    if (time == 'month') {//本月
        $('.percentTypeMonth').addClass('active-second');
        $('.percentTypeAll').removeClass('active-second');
        $('.percentTypeTopMonth').removeClass('active-second');
        $('.percentTypeWeek').removeClass('active-second');
        $("#percentTypeDataType").val("thisMonth");
        oppContractTypeProportion("thisMonth");
    }
    if (time == 'week') {//本周
        $('.percentTypeWeek').addClass('active-second');
        $('.percentTypeAll').removeClass('active-second');
        $('.percentTypeTopMonth').removeClass('active-second');
        $('.percentTypeMonth').removeClass('active-second');
        $("#percentTypeDataType").val("thisWeek");
        oppContractTypeProportion("thisWeek");
    }
}
//成交
function percentDealSelectTime(time){
    if (time == 'all') {//全部
        $('.percentDealAll').addClass('active-second');
        $('.percentDealTopMonth').removeClass('active-second');
        $('.percentDealMonth').removeClass('active-second');
        $('.percentDealWeek').removeClass('active-second');
        $("#percentDealDataType").val("all");
        oppTurnoverProportion("")
    }
    if (time == 'topMonth') {//上月
        $('.percentDealTopMonth').addClass('active-second');
        $('.percentDealAll').removeClass('active-second');
        $('.percentDealMonth').removeClass('active-second');
        $('.percentDealWeek').removeClass('active-second');
        $("#percentDealDataType").val("thisLastMonth");
        oppTurnoverProportion("thisLastMonth");
    }
    if (time == 'month') {//本月
        $('.percentDealMonth').addClass('active-second');
        $('.percentDealAll').removeClass('active-second');
        $('.percentDealTopMonth').removeClass('active-second');
        $('.percentDealWeek').removeClass('active-second');
        $("#percentDealDataType").val("thisMonth");
        oppTurnoverProportion("thisMonth");
    }
    if (time == 'week') {//本周
        $('.percentDealWeek').addClass('active-second');
        $('.percentDealAll').removeClass('active-second');
        $('.percentDealTopMonth').removeClass('active-second');
        $('.percentDealMonth').removeClass('active-second');
        $("#percentDealDataType").val("thisWeek");
        oppTurnoverProportion("thisWeek");
    }
}

//表格
function businessTableSelectTime(time){
    if (time == 'all') {//全部
        $('.businessTableAll').addClass('active-second');
        $('.businessTableTopMonth').removeClass('active-second');
        $('.businessTableMonth').removeClass('active-second');
        $('.businessTableWeek').removeClass('active-second');
        $("#businessTableDataType").val("all");
        businessTableInit("")
    }
    if (time == 'topMonth') {//上月
        $('.businessTableTopMonth').addClass('active-second');
        $('.businessTableAll').removeClass('active-second');
        $('.businessTableMonth').removeClass('active-second');
        $('.businessTableWeek').removeClass('active-second');
        $("#businessTableDataType").val("thisLastMonth");
        businessTableInit("thisLastMonth");
    }
    if (time == 'month') {//本月
        $('.businessTableMonth').addClass('active-second');
        $('.businessTableAll').removeClass('active-second');
        $('.businessTableTopMonth').removeClass('active-second');
        $('.businessTableWeek').removeClass('active-second');
        $("#businessTableDataType").val("thisMonth");
        businessTableInit("thisMonth");
    }
    if (time == 'week') {//本周
        $('.businessTableWeek').addClass('active-second');
        $('.businessTableAll').removeClass('active-second');
        $('.businessTableTopMonth').removeClass('active-second');
        $('.businessTableMonth').removeClass('active-second');
        $("#businessTableDataType").val("thisWeek");
        businessTableInit("thisWeek");
    }
}

//排名
function rankSelect(time) {
    if (time == 'win') {//全部
        $('.winRank').addClass('active-second');
        $('.allRank').removeClass('active-second');
        $("#rank").val("win");
        rank(1);
    }
    if (time == 'all') {//上月
        $('.allRank').addClass('active-second');
        $('.winRank').removeClass('active-second');
        $("#rank").val("all");
        rank(2);
    }
}

//商机转态初始化
function barInitData(dateType){
    $.ajax({
        type: 'post',
        dataType: "json",
        url: '/opportunity/oppStatusStatistics',
        contentType: "application/json;charset=utf-8",
        data:JSON.stringify({
            dateType:dateType,
            bs:0
        }),
        success: (function (result) {
            if (result.code == "000000") {
                barInit('businessChart',result.data)
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

/**
 * 商机数据
 */
function businessMess(){
    $.ajax({
        type: 'post',
        dataType: "json",
        url: '/opportunity/oppDataStatistics',
        data:{},
        success: (function (result) {
            if (result.code == "000000") {
                let data = result.data;
                let list = [
                    {name:'成交额度',topMonth:data.lastMonth.transactionAmount,month:data.thisWeek.transactionAmount,week:data.thisMonth.transactionAmount},
                    {name:'会员新增',topMonth:data.lastMonth.newMembers,month:data.thisWeek.newMembers,week:data.thisMonth.newMembers},
                    {name:'商机新增',topMonth:data.lastMonth.newOpportunity,month:data.thisWeek.newOpportunity,week:data.thisMonth.newOpportunity},
                    {name:'赢单新增',topMonth:data.lastMonth.newWinOrder,month:data.thisWeek.newWinOrder,week:data.thisMonth.newWinOrder},
                    {name:'待回款额度',topMonth:data.lastMonth.amountReturned,month:data.thisWeek.amountReturned,week:data.thisMonth.amountReturned},
                    {name:'联系人新增',topMonth:data.lastMonth.newContact,month:data.thisWeek.newContact,week:data.thisMonth.newContact},
                    {name:'电话量新增',topMonth:data.lastMonth.newCallVolume,month:data.thisWeek.newCallVolume,week:data.thisMonth.newCallVolume},
                ];
                let html = '';
                $.each(list,function(index,item){
                    html+= `  <li>
                            <span>${item.name}</span>
                            <span>${item.topMonth == null?'':item.topMonth}</span>
                            <span>${item.month == null?'':item.month}</span>
                            <span>${item.week == null?'':item.week}</span>
                        </li>`
                })
                $('#businessMessList').append(html)
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}


/**
 * 商机占比
 */
function oppContractProportion(dateType){
    $.ajax({
        type: 'post',
        dataType: "json",
        url: '/opportunity/oppContractProportion',
        data:{
            dateType:dateType
        },
        async:false,
        success: (function (result) {
            if (result.code == "000000") {
                let percentList = [
                        {value: '', name: '其他合同'},
                        {value: '', name: '商机合同'},
                    ];
                $.each(result.data,function(index,item){
                    if(result.data[index].productName == 0){
                        percentList[0].value = result.data[index].proportion
                    }else if(result.data[index].productName == 1){
                        percentList[1].value = result.data[index].proportion
                    }
                })
                console.log(percentList)
                //商机合同占比
                pieInit('opportunityContract','',percentList,['商机合同','其他合同'])
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

/**
 * 商机类型
 */
function oppContractTypeProportion(dateType){
    $.ajax({
        type: 'post',
        dataType: "json",
        url: '/opportunity/oppContractTypeProportion',
        data:{
            dateType:dateType
        },
        async:false,
        success: (function (result) {
            if (result.code == "000000") {
                console.log(result)
                let percentList1 = [
                    {value: '', name: '续费'},
                    {value: '', name: '新单'},
                    {value: '', name: '非会员'},
                ];
                $.each(result.data,function(index,item){
                    if(result.data[index].productName == 4){
                        percentList1[0].value = result.data[index].proportion;
                    }else if(result.data[index].productName == 2){
                        percentList1[1].value = result.data[index].proportion;
                    }else if(result.data[index].productName == 1){
                        percentList1[2].value = result.data[index].proportion;
                    }
                })
                console.log(percentList1)
                //商机合同类型比例
                pieInit('opportunityContractType','',percentList1,['新单','续费','非会员'])
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

/**
 * 商机成交
 */
function oppTurnoverProportion(dateType){
    $.ajax({
        type: 'post',
        dataType: "json",
        url: '/opportunity/oppTurnoverProportion',
        data:{
            dateType:dateType
        },
        async:false,
        success: (function (result) {
            if (result.code == "000000") {
                let percentList2 = [
                    {value: '', name: '总金额'},
                    {value: '', name: '商机合同金额'},
                ];
                $.each(result.data,function(index,item){
                    if(result.data[index].productName == 0){
                        percentList2[0].value = result.data[index].proportion;
                    }else if(result.data[index].productName == 1){
                        percentList2[1].value = result.data[index].proportion;
                    }
                })
                //商机成交比例
                pieInit('businessOpportunity','',percentList2,['商机合同金额','总金额'])
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

/**
 *商机分析表格初始化
 */
function businessTableInit(dateType){
    //先销毁表格
    $businessTable.bootstrapTable('destroy');
    $businessTable.bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        url: '/opportunity/opportunityFollowIntentionZb',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: true,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: false,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '',//cell没有值时显示
        // sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'formId',
        idField: 'formId',
        // pageSize: 10,//每页的记录行数
        // pageNumber: 1,//初始化加载第1页，默认第1页
        // pageList: "[5, 10, 15, 20]",//可供选择的每页的行数
        fixedColumns: true,     // 冻结列
        fixedNumber: 4,         // 左侧固定列
        showHeader:false,
        queryParams: {
            dateType:dateType
        },//查询参数
        columns: [
            {title: '', field: 'opportunityStatus',align: 'center', valign: 'middle',formatter: genderOpt},
            {title: '', field: 'stutsFollow', align: 'center', valign: 'middle'},
            {title: '', field: 'a', align: 'center', valign: 'middle',formatter: genderOpt1},
            {title: '', field: 'followProportion', align: 'center', valign: 'middle'},
            {title: '', field: 'a', align: 'center', valign: 'middle',formatter: genderOpt2},
            {title: '', field: 'intentionProportion', align: 'center', valign: 'middle'},
        ],
        responseHandler: function (result) {
            if (result.code == "000000"){
                var obj = {
                    "rows":result.data,
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    })
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index){
    //1: 初步洽谈 2: 需求确定 3: 方案报价 4: 谈判 5: 洽谈合同 6: 赢单 7: 输单
    if(value == 1){
        return [
            '<span>初步洽谈</span>',
        ].join('');
    }else if(value == 2){
        return [
            '<span>需求确定</span>',
        ].join('');
    }else if(value == 3){
        return [
            '<span>方案报价</span>',
        ].join('');
    }else if(value == 4){
        return [
            '<span>谈判</span>',
        ].join('');
    }else if(value == 5){
        return [
            '<span>洽谈合同</span>',
        ].join('');
    }else if(value == 6){
        return [
            '<span>赢单</span>',
        ].join('');
    }else if(value == 7){
        return [
            '<span>输单</span>',
        ].join('');
    }

}
function genderOpt1(value, row, index){
    return [
        '<span>跟进占比</span>',
    ].join('');
}
function genderOpt2(value, row, index){
    return [
        '<span>意向占比</span>',
    ].join('');
}

/**
 * 柱图初始化
 */
function barInit(id,data){
    let dom = document.getElementById(id);
    let myChart = echarts.init(dom);
    let option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {            // Use axis to trigger tooltip
                type: 'shadow'        // 'shadow' as default; can also be 'line' or 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'value',
            axisLabel:{
                show:false,
            },
            splitLine: {
                show:false,
            },
            axisLine:{
                show:false,
            },
            axisTick: {
                show:false,
            } ,
        },
        yAxis: {
            type: 'category',
            data: ['初步洽谈', '需求确定', '方案报价', '谈判', '洽谈合同', '赢单', '输单'],
            splitLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            axisLine: {
                show: false
            },
        },
        series: [
            {
                type: 'bar',
                stack: 'total',
                label: {
                    show: true
                },
                emphasis: {
                    focus: 'series'
                },
                itemStyle: {
                    normal: {
                        barBorderRadius: 30,
                        color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [{
                            offset: 0,
                            color: '#5977ff'
                        }, {
                            offset: 1,
                            color: '#5977ff'
                        }]),
                    },
                },
                barWidth: 20,
                data:data
            }
        ]
    };
    myChart.setOption(option);
    window.addEventListener("resize",function(){
        myChart.resize();
    });
}

function pieInit(id,title,data,legend_data) {
    let dom = document.getElementById(id);
    let myChart = echarts.init(dom);
    let option = {
        title: {
            text: title,
            left: 'left',

            textStyle: {
                color: '#333333',
                fontWeight: 'bold',
                fontSize:16
            }
        },
        tooltip: {
            trigger: 'item'
        },
        legend: {     // 饼图外的各项数据item
            orient: 'vertical',
            icon: 'circle',
            right: '6%',
            top: '6%',
            itemWidth: 8,
            itemHeight: 8,

            data: legend_data,
        },
        // color:['#87e7ff','#43aeff','#5977ff'],
        color:['#52CCA3','#6699FF','#B2CDFF'],
        series: [
            {
                name:title,
                type: 'pie',
                radius: '60%',
                label: {
                    normal: {
                        position: 'inner',
                        show : false
                    }
                },
                emphasis: {
                    itemStyle: {
                        // shadowBlur: 10,
                        // shadowOffsetX: 2,
                        // shadowColor: 'rgba(255, 255, 255, 1)'
                        borderColor: '#fff',
                        borderWidth: 4
                    }
                },
                data:data,
            }
        ],
        grid: {
            top:'10%',
            left:'2%',
            right:'2%',
            bottom:'2%'
        }
    };
    myChart.setOption(option);
    window.addEventListener("resize",function(){
        myChart.resize();
    });
}

function rank(bs){
    $.ajax({
        type: 'post',
        dataType: "json",
        url: '/opportunity/oppOfNumber',
        data:{
            bs:bs
        },
        success: (function (result) {
            if (result.code == "000000") {
                let rankHtml = '';
                $.each(result.data,function(index,item){
                    rankHtml+=`
                                <li>
                                    <div class="pankImg">
                                        <img src=${item.accessUrl} alt="" title=${item.userName}>
                                    </div>
                                    <div class="rankMess">
                                        <span>${item.userName}</span>
                                        <span>商机总数：<i>${item.zcount == null?'0':item.zcount}</i><i style="margin-left: 20px">赢单商机：<i>${item.ycount == null?'0':item.ycount}</i></i></span>
                                    </div>
                                </li>
                                `
                })
                $('#rankList').html(rankHtml)
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}